package sg.edu.nus.iss.umpire.email;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sg.edu.nus.iss.umpire.dao.jpa.CompetitionDaoImpl;
import sg.edu.nus.iss.umpire.dao.jpa.UmpireDAOImpl;
import sg.edu.nus.iss.umpire.domain.Competition;
import sg.edu.nus.iss.umpire.domain.CompetitionDay;
import sg.edu.nus.iss.umpire.domain.Session;
import sg.edu.nus.iss.umpire.domain.Umpire;
import sg.edu.nus.iss.umpire.support.AppConstants;
import sg.edu.nus.iss.umpire.support.HttpMethod;
import sg.edu.nus.iss.umpire.support.Service;
import sg.edu.nus.iss.umpire.support.ServiceConfig;
import sg.edu.nus.iss.umpire.support.ServiceContext;

@SuppressWarnings("serial")
@ServiceConfig(path = "sendinvitations", method = HttpMethod.POST)
public class InviteUmpiresServlet implements Service {
	private EntityManager em;
	private static Logger log = Logger.getLogger(InviteUmpiresServlet.class.getCanonicalName());
	@Override
	public String serve(ServiceContext ctx) throws Exception {
		em = ctx.getEntityManager();
		List<Umpire> umpires = new UmpireDAOImpl(ctx.getEntityManager()).loadAll();
		for ( Umpire itrUmpire:umpires)
		{
			processInvitation(itrUmpire, ctx.getRequest(), ctx.getResponse());
		}
		
		return null;
	}

	  /**
	   * The method process the invitation request.
	   * 
	   * @param req : HTTP request from the task queue
	   * @param resp : HTTP response
	   * @throws IOException
	   */
	  private void processInvitation(Umpire umpire, HttpServletRequest req, HttpServletResponse resp)
	      throws IOException {
		 
	      String umpireEmail = umpire.getEmail();		  
		  String subject = "Umpire invitation";
		  String competitionKey = req.getParameter("competitionKey");
		  
		  String replyUrl = String.format(AppConstants.REPLY_INVITATION_URL, competitionKey);
		  String msgBody = createEmailMsg(replyUrl, req.getParameter("instruction"),competitionKey);

		  // send email to umpires
		  MailService mailService = new MailService();
		  mailService.send(umpireEmail, subject, msgBody);
	  }
	  private String createEmailMsg(String replyUrl, String instruction, String competitionKey) {
	      CompetitionDaoImpl compDao = new CompetitionDaoImpl(em);
	      String nl = System.getProperty("line.separator");
	      Competition comp = compDao.getByKey(Long.parseLong(competitionKey));
	      String msg = "Dear Umpires,"+nl+nl+
		      "%s (%s to %s) will need umpires on the following sessions"+nl+
		      "Please indicate your availability by visiting this url %s."+nl+nl+
		      "Time Slots"+nl+
		      "%s"+nl+
		      "Referee: %s"+nl+nl+
		      "Location: %s"+nl+nl+
		      "Instruction from Referee:"+nl+
		      "%s"+nl+nl+
		      "Thank you.";
	      
	      SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
	      String slots="";
	      for(CompetitionDay day : comp.getCompetitionDays()){
		  String d = day.getDate()+":";
		  for(Session s : day.getSessions())
		      d+=" " + s.getSlotName();
		  slots+=d+nl;
	      }
	      
	      msg = String.format(msg, comp.getName(),df.format(comp.getStartDate()),
		      df.format(comp.getEndDate()),replyUrl,slots,
		      comp.getRefereeName().trim(),comp.getLocation(),instruction.trim());
	      System.out.println(msg);
	      return msg;
	  }
}
